package com.atguigu.gulimall.member.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.MemberConstant;
import com.atguigu.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @auther Sherlock
 * @date 2020/8/28 21:55
 * @Description: 属于springMVC的拦截器 在执行目标方法之前，判断用户的登录状态。并封装传递给controller
 *
 *  springboot使用拦截器
 *  1、 创建一个 LoginUserInterceptor 实现 {link HandlerInterceptor}
 *  2、 把拦截器添加到springMVC中
 *  see GmallMemberWebConfiguration#addInterceptors(org.springframework.web.servlet.config.annotation.InterceptorRegistry)
 *
 *    registry.addInterceptor(LoginUserInterceptor).addPathPatterns("/**");  添加 cartInterceptor 拦截器并且拦截所有请求("/**)
 *
 */
@Component
@Slf4j
public class LoginUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try{
            log.info("调用类为：{}", ((HandlerMethod)handler).getBean().getClass().getName());
            log.info("调用方法为：{}", ((HandlerMethod)handler).getMethod().getName());
        } catch (Exception e){
            log.info("com.sherlock.gmall.member.interceptor.LoginUserInterceptor#preHandle have Exception, msg is {}", e.getMessage());
        }

        /**
         *
         * 查询邮费信息时需要远程直接调用这个系统的接口，在request的session中获取不到member，会被阻拦，所以需要直接放行
         *
         * 其他系统远程调用的需要放行，因为request的session中获取不到member，但是直接访问本接口的都需要拦截查看登录情况
         *
         * @see com.sherlock.gmall.ware.rabbitListener.ReleaseLockStock#handStockLockedRelease(com.sherlock.common.to.mq.StockLockedTo, org.springframework.amqp.core.Message, com.rabbitmq.client.Channel)
         */

        StringBuffer requestURL = request.getRequestURL();
        log.info("request Url is {}", requestURL);

        // 远程调用本系统的系统，只要进行的Feign的配置，就会携带请求的session信息，可以获取到登录信息
        // 但是 这个请求是从 com.sherlock.gmall.ware.service.impl.WareInfoServiceImpl#getFare是这个的远程调用， 这个是从confirm.html发过来的get请求，在请求头中没有包含session信息，所以需要过滤掉
        for (String whiteUrl : MemberConstant.MEMBER_REQUEST_WHITE_LIST) {
            if(new AntPathMatcher().match(whiteUrl, requestURL.toString())){
                return true;
            }
        }

        if (request.getRequestURL().toString().endsWith("swagger-ui.html")) {
            return true;
        }

        HttpSession session = request.getSession();
        MemberRespVo member = (MemberRespVo)session.getAttribute(AuthServerConstant.GULIMALL_LOGIN_USER);

        if (member != null){
            // 用户登录了
            loginUser.set(member);
            return true;
        } else {
            request.getSession().setAttribute("msg", "请先登录");
            response.sendRedirect("http://auth.gulimall.com");
            return false;
        }

    }

    /**
     * 从threadLocal中获取UserInfoTo,然后获取用户是否登录过，没登录过就在
     * 请求返回之前如果cookie里面没有uer-key就往里面放1个，最大时间为1个月
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
   /* @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.isTemp()) {
            Cookie cookie = new Cookie(GmallCartConstant.GMALL_TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gmall.com");
            cookie.setMaxAge(GmallCartConstant.GMALL_TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        loginUser.remove();
    }*/
}
